import React, { useState,useRef } from "react";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Checkbox, message } from "antd";
import { ProFormText, LoginForm, ProFormCheckbox } from "@ant-design/pro-form";
import { history, useModel } from "umi";
import { fetchSingIn } from "@/api/admin";
import styles from "./index.less";

const Login = () => {
  const formRef = useRef();
  const [rember, setRember] = useState(!!localStorage.getItem("password"));
  const { initialState, setInitialState } = useModel("@@initialState");
  const fetchUserInfo = async (adminInfo) => {
    const userInfo = await initialState?.fetchUserInfo?.();
    console.log("userInfo", initialState);
    if (userInfo) {
      await setInitialState((s) => ({ ...s, currentUser: { ...userInfo } }));
    }
    const { routes } = initialState;
    const { permissionCodes } = adminInfo;
    const first = permissionCodes[0];
    let path = "/";
    // routes.forEach((item) => {
    //   if (item.access === first) {
    //     path = item.path;
    //     if (item.routes) {
    //       path = item.routes[0].path;
    //     }
    //   }
    // });
    console.log("path===", path);
    history.push(path);
  };

  const handleSubmit = async (values) => {
    try {
      // 登录
      const postData = {
        ...values,
        // password: window.btoa(values.password),
      };
      const res = await fetchSingIn(postData);
      if (res.status === "success") {
        message.success("登录成功！");
        const adminInfo = res.data;
        localStorage.setItem("adminInfo", JSON.stringify(adminInfo));
        await fetchUserInfo(adminInfo);
      } else {
        // message.error(res.msg);
      }
    } catch (error) {}
  };

  return (
    <div className={styles.container}>
      {/* <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang />}
      </div> */}
      <div className={styles.content}>
        <LoginForm
          formRef={formRef}
          // logo={<img alt="logo" src="/logo.svg" />}
          title="星链悦享书包管理系统"
          onFinish={async (values) => {
            await handleSubmit(values);
          }}
          initialValues={{
            username: localStorage.getItem("username") || "",
            password: localStorage.getItem("password") || "",
          }}
        >
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: "large",
                prefix: <UserOutlined className={styles.prefixIcon} />,
              }}
              placeholder="账号"
              rules={[
                {
                  required: true,
                  message: "请输入账号",
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: "large",
                prefix: <LockOutlined className={styles.prefixIcon} />,
              }}
              placeholder="密码"
              rules={[
                {
                  required: true,
                  message: "请输入密码",
                },
              ]}
            />
            <div style={{ display: "flex", justifyContent: "flex-end" }}>
              <Checkbox
                checked={rember}
                onChange={(e) => {
                  setRember(e.target.checked);
                  const values = formRef.current.getFieldsValue();
                  if (e.target.checked) {
                    localStorage.setItem("username", values.username);
                    localStorage.setItem("password", values.password);
                  } else {
                    localStorage.removeItem("username");
                    localStorage.removeItem("password");
                  }
                }}
                style={{ marginBottom: 10 }}
              >
                记住密码
              </Checkbox>
            </div>
          </>
        </LoginForm>
      </div>
    </div>
  );
};

export default Login;
